<template>
  <el-card shadow="hover">
    <el-button
      type="primary"
      :icon="Plus"
      @click="showTrademarkDialog({ id: 0, tmName: '', logoUrl: '' })"
    >
      添加
    </el-button>

    <el-table :data="totalList" border class="mt-20">
      <el-table-column label="序号" width="60" type="index" align="center" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column label="品牌LOGO">
        <template v-slot="{ row }">
          <img
            :src="row.logoUrl"
            :alt="row.tmName"
            style="width: 100px; height: 60px"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="{ row }">
          <el-button
            size="small"
            :icon="Edit"
            type="warning"
            @click="showTrademarkDialog(row)"
          ></el-button>
          <el-button
            size="small"
            type="danger"
            :icon="DeleteFilled"
            @click="delDateTrademark(row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9, 12]"
      layout=" prev, pager, next, jumper,->, sizes , total"
      :total="total"
      @size-change="getTrademarkList"
      @current-change="getTrademarkList"
    />

    <el-dialog
      v-model="visible"
      :show-close="false"
      :title="`${formData.id ? '修改' : '添加'} 品牌`"
    >
      <el-form
        label-width="120px"
        ref="formRef"
        :model="formData"
        :rules="formRules"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input placeholder="请输入品牌名称" v-model="formData.tmName" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${BASE_URL}/admin/product/fileUpload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            accept="image/jpeg,image/png"
          >
            <img
              v-if="formData.logoUrl"
              :src="formData.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png文件，且不超过200kb
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="submit"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "Trademark",
};
</script>

<script lang="ts" setup>
import { Plus, DeleteFilled, Edit } from "@element-plus/icons-vue";
import { ref, onMounted, reactive } from "vue";
import type {
  TrademarkList,
  TrademarkItem,
} from "@/api/product/model/trademarkModel";
import { ElMessage, ElMessageBox } from "element-plus";
import type { UploadProps } from "element-plus";
import {
  getTrademarkListApi,
  addTrademarkApi,
  updateTrademarkApi,
  delTrademarkApi,
} from "@/api/product/trademark";

const visible = ref(false);
const currentPage = ref(1);
const pageSize = ref(3);
const total = ref(0);

const BASE_URL = import.meta.env.VITE_API_URL;
const imageUrl = ref("");
const displayVisible = () => {
  visible.value = true;
};
// const handleSizeChange = () => {};
// const handleCurrentChange = () => {};

const totalList = ref<TrademarkList>([]);

const formRef = ref();

const showTrademarkDialog = (row: TrademarkItem) => {
  formData.tmName = row.tmName;
  formData.logoUrl = row.logoUrl;
  formData.id = row.id;
  formRef.value?.clearValidate();
  visible.value = true;
};

//提交表单
const submit = async () => {
  await formRef.value.validate();
  const { tmName, logoUrl, id } = formData;
  if (id) {
    await updateTrademarkApi(formData);
  } else {
    await addTrademarkApi(tmName, logoUrl);
  }
  visible.value = false;
  ElMessage.success(`${id ? "修改" : "添加"}品牌成功~`);
  getTrademarkList();
};

//表单数据
const formData = reactive({
  id: 0,
  tmName: "",
  logoUrl: "",
});
//表单效验规则
const formRules = reactive({
  tmName: [
    { required: true, message: "请输入品牌名称", trigger: "blur" },
    { min: 2, max: 10, message: "格式不正确", trigger: "blur" },
  ],
});

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response
  // uploadFile
) => {
  formData.logoUrl = response.data;
  formRef.value.clearValidate(["logoUrl"]);
};
//图片效验规则
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const fileType = ["image/jpeg", "image/png"];
  if (!fileType.includes(rawFile.type)) {
    ElMessage.error("图片格式错误");
    return false;
  } else if (rawFile.size / 1024 > 200) {
    ElMessage.error("图片大小错误");
    return false;
  }
  return true;
};

onMounted(() => {
  getTrademarkList();
});
//获取数据
const getTrademarkList = async () => {
  const res = await getTrademarkListApi(currentPage.value, pageSize.value);
  (total.value = res.total), (totalList.value = res.records);
};

/************************************************ */
const delDateTrademark = (row: TrademarkItem) => {
  ElMessageBox.confirm(`您确定要删除${row.tmName} 品牌吗？`, "警告", {
    confirmButtonText: "确认删除",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await delTrademarkApi(row.id);
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      getTrademarkList();
    })
    .catch(() => {
      // ElMessage({
      //   type: 'info',
      //   message: 'Delete canceled',
      // })
    });
};
</script>

<style scoped lang="scss">
.trademark__table {
  margin: 20px 0;
}

.avatar-uploader {
  :deep() {
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
